package com.leyou.sms.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class SendSms {
    @Autowired
    private IAcsClient client;
    @Autowired
    private SmsProperties smsProperties;

    public  void sendSms(String phone,String templateCode,String templateParam,String signName) {
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsProperties.getDomain());
        request.setSysVersion(smsProperties.getVersion());
        request.setSysAction(smsProperties.getAction());
        request.putQueryParameter("RegionId", smsProperties.getRegionID());
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            Map<String, String> map = JsonUtils.toMap(response.getData(), String.class, String.class);
            if(!"OK".equals(map.get("Code"))){
                log.error("短信发送失败，原因是：{}",map.get("Message"));
                throw new LyException("短信发送失败",500);
            }
            log.info("发送短信成功");
        } catch (ServerException e) {
            log.error("短信发送失败，服务端异常",e);
        } catch (ClientException e) {
            log.error("短信发送失败,客户端异常",e);
        }
    }

    public  void sendVerificationCode(String phone,String code){
        try {
            String param = String.format("{\"code\":\"%s\"}",code);
            sendSms(phone,smsProperties.getVerifyCodeTemplate(),param,smsProperties.getSignName());
        } catch (Exception e) {

        }

    }
}

